from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
from django.views import View
from django import forms

import os


# 登录表单（可选，用于错误显示）
class LoginForm(forms.Form):
    username = forms.CharField(label='用户名', max_length=150)
    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    remember = forms.BooleanField(label='记住我', required=False)


# Create your views here.

# @require_http_methods(["POST"])
def login_view(request):
    return render(request, 'login.html')


class LoginView(View):
    def get(self, request):
        if request.user.is_authenticated:
            return redirect('/')
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')

        if not username or not password:
            return render(request, 'login.html', {
                'form': LoginForm(request.POST),
                'error': '请输入用户名和密码'
            })

        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)

            # 设置 session 过期（如果 remember 选中）
            if request.POST.get('remember'):
                request.session.set_expiry(1209600)  # 2周
            else:
                request.session.set_expiry(0)  # 浏览器关闭即失效
            return render(request, 'home.html', )
        else:
            return render(request, 'login.html', {
                'form': LoginForm(request.POST),
                'error': '用户名或密码错误'
            })


# @login_required
def index_view(request):
    return render(request, 'home.html')


# @login_required
# @require_http_methods(["POST"])
def logout_view(request):
    logout(request)
    return render(request, 'login.html')


@method_decorator(csrf_protect, name="dispatch")
@method_decorator(login_required, name="dispatch")
class UploadView(View):
    def post(self, request, *args, **kwargs):
        if 'file' not in request.FILES:
            return JsonResponse({"error": "文件未上传"}, status=400)

        uploaded_file = request.FILES['file']

        file_path = f"/tmp/app{kwargs["app_id"]}_{uploaded_file.name}"
        with open(file_path, 'wb+') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)

        return JsonResponse({'status': 'success', 'filename': uploaded_file.name}, status=200)

    def get(self, request, *args, **kwargs):
        return render(request, template_name="home.index")
